<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getCaseDetail, updateCase } from '@/api/kg/case';
import { ElMessage, FormInstance } from 'element-plus';
import { getCaseDifficulty, getCaseStatus, formRules } from '@/views/kg/case/utils/columns';
import { Plus } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();
const loading = ref(false);

// 表单数据
const formData = ref({
  nodeId: null,
  description: '',
  cover: '',
  type: '',
  difficulty: 1,
  status: 0,
  auditMessage: '',
  auditor: null,
  createTime: '',
  updateTime: '',
});

// 案例类型选项
const caseTypeOptions = [
  { label: '基础知识', value: '基础知识' },
  { label: '进阶案例', value: '进阶案例' },
  { label: '实战项目', value: '实战项目' },
  { label: '课程练习', value: '课程练习' },
];

// 案例难度选项
const difficultyOptions = [
  { label: '简单', value: 1 },
  { label: '中等', value: 2 },
  { label: '困难', value: 3 },
];

// 上传成功回调
const handleUploadSuccess = (res: any) => {
  if (res && res.url) {
    formData.value.cover = res.url;
  }
};

// 获取案例详情
const fetchCaseDetail = async (id: number) => {
  loading.value = true;
  try {
    const res = await getCaseDetail(id);
    formData.value = res;
  } catch (error) {
    console.error('获取案例详情失败:', error);
    ElMessage.error('获取案例详情失败');
  } finally {
    loading.value = false;
  }
};

// 保存案例
const saveCase = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        await updateCase(formData.value);
        ElMessage.success('保存成功');
      } catch (error) {
        console.error('保存案例失败:', error);
        ElMessage.error('保存案例失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 返回列表页
const goBack = () => {
  router.push('/kg/course');
};

onMounted(() => {
  const id = route.params.id;
  if (id) {
    fetchCaseDetail(Number(id));
  } else {
    ElMessage.error('案例ID不存在');
    goBack();
  }
});
</script>

<template>
  <div class="case-detail bg-bg_color p-6">
    <div class="mb-4 flex justify-between items-center">
      <h2 class="text-xl font-bold">案例详情</h2>
      <div>
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" :loading="loading" @click="saveCase">保存</el-button>
      </div>
    </div>

    <el-card class="box-card">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="mt-4">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="案例封面" prop="cover">
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
              >
                <img v-if="formData.cover" :src="formData.cover" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="案例状态">
              <el-tag :type="getCaseStatus(formData.status)" effect="light" class="mr-2">
                {{ getCaseStatus(formData.status, true) }}
              </el-tag>
              <span v-if="formData.createTime" class="text-gray-500 text-sm ml-4">
                创建时间: {{ formData.createTime }}
              </span>
            </el-form-item>

            <el-form-item label="案例描述" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入案例描述" />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="案例类型" prop="type">
                  <el-select v-model="formData.type" placeholder="请选择案例类型" class="w-full">
                    <el-option v-for="item in caseTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="案例难度" prop="difficulty">
                  <el-select v-model="formData.difficulty" placeholder="请选择案例难度" class="w-full">
                    <el-option v-for="item in difficultyOptions" :key="item.value" :label="item.label" :value="item.value">
                      <template #default="{ item }">
                        <el-tag :type="getCaseDifficulty(item.value)" size="small" class="mr-2">{{ item.label }}</el-tag>
                        {{ item.label }}
                      </template>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <!-- 审核信息 -->
        <el-divider content-position="left">审核信息</el-divider>
        <el-form-item v-if="formData.status === 3" label="审核意见">
          <el-input v-model="formData.auditMessage" type="textarea" :rows="2" disabled />
        </el-form-item>

        <!-- 详情内容 -->
        <el-divider content-position="left">案例内容</el-divider>
        <el-form-item label="内容编辑">
          <div class="border rounded p-4 min-h-[400px]">
            <!-- 这里可以根据需要集成富文本编辑器或Markdown编辑器 -->
            <el-input v-model="formData.description" type="textarea" :rows="15" placeholder="请输入案例详细内容" />
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.case-detail {
  min-height: calc(100vh - 120px);
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }

  .avatar {
    width: 120px;
    height: 120px;
    display: block;
    object-fit: cover;
  }
}
</style>
